

import 'dart:async';
import 'dart:io';


import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:custom_social_share/custom_social_share.dart';
import 'package:date_format/date_format.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/pdf.dart';
import 'package:printing/printing.dart';
import 'package:share_extend/share_extend.dart';
import 'package:simple_tooltip/simple_tooltip.dart';
import 'package:smart_freezer/core/model/product_model.dart';
import 'package:smart_freezer/core/resources/app_config.dart';
import 'package:smart_freezer/core/resources/icon_names.dart';
import 'package:smart_freezer/core/resources/routers.dart';
import 'package:smart_freezer/core/service/api/app_api.dart';
import 'package:smart_freezer/core/service/service/result_data.dart';
import 'package:smart_freezer/core/utils/color_util.dart';
import 'package:smart_freezer/core/utils/logs.dart';
import 'package:smart_freezer/core/utils/tr_extension.dart';
import 'package:smart_freezer/generated/locale_keys.g.dart';
import 'package:smart_freezer/ui.pages/home/device/reporter/report.dart';
import 'package:syncfusion_flutter_xlsio/xlsio.dart' as Flutter_Xlsio ;
import 'package:ty_smart_home/ty_smart_home.dart';

import '../../../core/utils/local_storage.dart';
import '../../../core/view/item_select_widget.dart';
import 'line_chart.dart';


class DeviceDetail extends StatefulWidget {
  const DeviceDetail({Key? key}) : super(key: key);

  @override
  State<DeviceDetail> createState() => _DeviceDetailState();
}

class _DeviceDetailState extends State<DeviceDetail> with TickerProviderStateMixin  {

  List _typeList = [
    LocaleKeys.device_info_one_hour.trc(),
    LocaleKeys.device_info_one_day.trc(),
    LocaleKeys.device_info_one_week.trc(),
    LocaleKeys.device_info_one_month.trc(),
    LocaleKeys.device_info_three_month.trc(),
    LocaleKeys.device_info_half_year.trc(),
    LocaleKeys.device_info_one_year.trc()
  ];
  List<String> _xList = [];
  List<double> _yList = [];
  List<String> _x2List = [];
  List<double> _y2List = [];

  late TabController _tabController;
  int tabSelectIndex = 0;

  bool isExpand = false;

  List _itemList = [{"icon": IconNames.tep_icon01, "title": LocaleKeys.device_info_device_info.trc(), "route": LCRouter.device_info},
    {"icon": IconNames.tep_icon02, "title": LocaleKeys.device_info_device_setting.trc(), "route": LCRouter.device_setting},
    {"icon": IconNames.tep_icon03, "title": LocaleKeys.device_info_warn_list.trc(), "route": LCRouter.home_warn_info},
  ];

  final _productId = Get.arguments as String;
  ProductModel _productModel = ProductModel();

  Timer? _refreshTimer;

  bool isDarkMode = LocalStorage.getThemeMode() == 1;

  @override
  void initState() {
    super.initState();

    _tabController = TabController(length: _typeList.length, vsync: this, initialIndex: tabSelectIndex);
    // 获取设备信息
    _getDeviceInfo();
    // 获取温度记录
    _getTempList();

    _startTimer();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();

    _stopRefreshTimer();
  }

  @override
  Widget build(BuildContext context) {

    logs("_productModel: ${_productModel.highTemperature}, ${_productModel.lowerTemperature}");
    // 温度过高
    bool isNotNormal = _productModel.highTemperature.isNotEmpty || _productModel.lowerTemperature.isNotEmpty ||
                       _productModel.t1Failure.isNotEmpty || _productModel.t2Failure.isNotEmpty || _productModel.t3Failure.isNotEmpty ||
                       _productModel.condenserClean.isNotEmpty || _productModel.doorOpen.isNotEmpty;

    return Scaffold(
      appBar: AppBar(
        // backgroundColor: Colors.white,
        elevation: 0,
        leadingWidth: 50,
        leading: InkWell(
          onTap: () {
            Get.back();
          },
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 9, 0, 9),
            child: Icon(Icons.arrow_back_ios_rounded),
          ),
        ),
        title: Text("${_productModel.code} ${_productModel.modelName} ${_productModel.name}", style: TextStyle(fontSize: 18),),
        centerTitle: true,
      ),
      body: Container(
        width: MainCommon.screenWidth,
        padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
        color: isDarkMode ? Colors.black : Color(0xFFF1F3F8),
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  children: [

                    // 设备异常或者离线
                    isNotNormal || _productModel.networkStatus == 2 ? InkWell(
                      onTap: () {
                        if(_productModel.networkStatus == 1 && _productModel.condenserClean.isNotEmpty){ // 处理设备在线时的冷凝器报警异常
                          _lengningqiClear();
                        }
                      },
                      child: Container(
                        child: Text(
                          _productModel.warningMessage,
                          style: TextStyle(color: Colors.red), textAlign: TextAlign.center,
                        ),
                        width: MainCommon.screenWidth,
                        height: 40,
                        color: HexColor("#FDD4DC"),
                        alignment: Alignment.center,
                      ),
                    ) : Container(height: 20,),

                    // t1, t2
                    Container(
                      padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          // 温度t1
                          Tooltip(
                            message: LocaleKeys.other_t1_tip.trc(),
                            child: Container(
                              decoration: BoxDecoration(
                                color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
                                borderRadius: BorderRadius.circular(5),
                              ),
                              height: 110,
                              padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Image.asset(IconNames.tep_t1, width: 30,),
                                  SizedBox(height: 5,),
                                  Container(
                                    child: Row(
                                      crossAxisAlignment: CrossAxisAlignment.end,
                                      children: [
                                        Text("${_productModel.networkStatus == 1 ? _productModel.temperatureOne : "--"}", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25)),
                                        Column(
                                          children: [
                                            Text("℃", style: TextStyle(fontSize: 16),),
                                            SizedBox(height: 2,),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                  SizedBox(height: 5,),
                                  // Row(
                                  //   children: [
                                  //     Text("${isNotNormal ? "T1${isMoreHigh ? LocaleKeys.device_info_wendu_up.trc() : LocaleKeys.device_info_wendu_low.trc()}" : LocaleKeys.device_info_wendu_normal.trc()}", style: TextStyle(color: Colors.grey, fontSize: 13),),
                                  //     Image.asset(IconNames.tep_nor, width: 15,)
                                  //   ],
                                  // ),
                                ],
                              ),
                            ),
                          ),

                          // 温度t2
                          Tooltip(
                            message: LocaleKeys.other_t2_tip.trc(),
                            child: Container(
                              decoration: BoxDecoration(
                                color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
                                borderRadius: BorderRadius.circular(5),
                              ),
                              padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
                              height: 110,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Image.asset(IconNames.tep_t2, width: 30,),
                                  SizedBox(height: 5,),
                                  Container(
                                    child: Row(
                                      crossAxisAlignment: CrossAxisAlignment.end,
                                      children: [
                                        Text("${_productModel.networkStatus == 1 ? _productModel.temperatureTwo : "--"}", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25)),
                                        Column(
                                          children: [
                                            Text("℃", style: TextStyle(fontSize: 16),),
                                            SizedBox(height: 2,),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                  SizedBox(height: 5,),
                                  // Row(
                                  //   children: [
                                  //     Text("${isNotNormal ? "T2${isMoreHigh ? LocaleKeys.device_info_wendu_up.trc() : LocaleKeys.device_info_wendu_up.trc()}" : LocaleKeys.device_info_wendu_normal.trc()}", style: TextStyle(color: Colors.grey, fontSize: 13),),
                                  //     Image.asset(IconNames.tep_nor, width: 15,)
                                  //   ],
                                  // ),
                                ],
                              ),
                            ),
                          ),

                          // 刷新数据, 打印
                          Container(
                            height: 110,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: [
                                // 刷新数据
                                InkWell(
                                  onTap: (){
                                    _getDeviceInfo();
                                    _getTempList();
                                  },
                                  child: Container(
                                    decoration: BoxDecoration(
                                      color: isDarkMode ? MainCommon.darkBlueMaterialColor : Color(0xFFEDFAFF),
                                      borderRadius: BorderRadius.circular(5),
                                    ),
                                    height: 50,
                                    padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
                                    child: Column(
                                      children: [
                                        Image.asset(IconNames.tep_refresh, height: 30,),
                                        Text(LocaleKeys.device_info_refresh_data.trc(), style: TextStyle(color: Colors.grey, fontSize: 12),)
                                      ],
                                    ),
                                  ),
                                ),

                                // 打印信息
                                InkWell(
                                  onTap: () {
                                    _showExportFileDialog();
                                  },
                                  child: Container(
                                    decoration: BoxDecoration(
                                      color: isDarkMode ? MainCommon.darkBlueMaterialColor : Color(0xFFEDFAFF),
                                      borderRadius: BorderRadius.circular(5),
                                    ),
                                    height: 50,
                                    padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
                                    child: Column(
                                      children: [
                                        Image.asset(IconNames.tep_xz, height: 30,),
                                        Text(LocaleKeys.device_info_export_pdf.trc(), style: TextStyle(color: Colors.grey, fontSize: 12),)
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),

                    SizedBox(height: 20,),
                    // 温度记录
                    Container(
                      decoration: BoxDecoration(
                        color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(10),
                          topRight: Radius.circular(10),
                        )
                      ),
                      padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
                      child: SingleChildScrollView(
                        child: Column(
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(LocaleKeys.device_info_wendu_list.trc(), style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),),
                                Row(
                                  children: [
                                    Row(
                                      children: [
                                        Image.asset(IconNames.tem_bx, width: 6,),
                                        Text(LocaleKeys.device_info_t1.trc(), style: TextStyle(fontSize: 12),),
                                      ],
                                    ),
                                    SizedBox(width: 5,),
                                    Row(
                                      children: [
                                        Image.asset(IconNames.tem_bx02, width: 6,),
                                        Text(LocaleKeys.device_info_t2.trc(), style: TextStyle(fontSize: 12),),
                                      ],
                                    )
                                  ],
                                )
                              ],
                            ),

                            // tab
                            Container(
                              // height: 400,
                              color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
                              child: DefaultTabController(
                                length: _typeList.length,
                                child: Column(
                                  children: [
                                    Container(
                                      height: 44,
                                      child: TabBar(
                                        controller: _tabController,
                                        tabs: _typeList.map((e) => Text(e)).toList(),
                                        isScrollable: true,
                                        indicatorColor: Color(0xFF234485),
                                        unselectedLabelColor: Colors.grey,
                                        unselectedLabelStyle: TextStyle(fontSize: 18),
                                        labelColor: Colors.grey,
                                        labelStyle: TextStyle(fontSize: 18),
                                        onTap: (index) {
                                          tabSelectIndex = index;
                                          _getTempList();
                                        },
                                      ),
                                    ),

                                    Container(
                                      width: MainCommon.screenWidth,
                                      height: 300,
                                      // color: Colors.red,
                                      margin: EdgeInsets.fromLTRB(0, 20, 0, 0),
                                      child: _xList.isEmpty ? Container() : LCLineChart(x1List: _xList, y1List: _yList, x2List: _x2List, y2List: _y2List,),
                                    ),
                                  ],
                                ),

                              ),
                            ),

                            // 查看数据列表
                            Container(
                              margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
                              child: Column(
                                children: [
                                  Offstage(
                                    offstage: !isExpand,
                                    child: Container(
                                      height: 110,
                                      width: MainCommon.screenWidth,
                                      child: EasyRefresh.custom(
                                        scrollDirection: Axis.horizontal,
                                        header: MaterialHeader(valueColor: AlwaysStoppedAnimation(isDarkMode ? Colors.white : Colors.black)),
                                        footer: MaterialFooter(valueColor: AlwaysStoppedAnimation(isDarkMode ? Colors.white : Colors.black)),
                                        firstRefresh: true,
                                        emptyWidget: _xList.isEmpty ? Center(
                                          child: Text(LocaleKeys.other_no_data.trc(), style: TextStyle(color: Colors.grey),),
                                        ) : null,
                                        slivers: [
                                          SliverList(
                                            delegate: SliverChildBuilderDelegate(
                                                  (context, columnIndex) {
                                                final title = columnIndex == 0 ? LocaleKeys.other_Area.trc() : _xList[columnIndex - 1];
                                                final t1 = columnIndex == 0 ? "T1" : _yList[columnIndex - 1];
                                                final t2 = columnIndex == 0 ? "T2" : _y2List[columnIndex - 1];

                                                final dataArr = [title, t1.toString(), t2.toString()];
                                                return Container(
                                                  child: Column(
                                                    children: List.generate(3, (rowIndex) {
                                                      return Container(
                                                        width: columnIndex == 0 ? 60 : 45,
                                                        height: rowIndex == 0  ? 30 : 40,
                                                        color: rowIndex == 1 ? (isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white) : (isDarkMode ? Color(0xFF313239) : Color(0xFFECEDEE)),
                                                        child: columnIndex > 0 ? Text(dataArr[rowIndex], style: TextStyle(color: isDarkMode ? Colors.grey : Colors.black),) :

                                                        Container(
                                                          decoration: BoxDecoration(
                                                            color: rowIndex == 1 ? Color(0xFFEF718F) : (rowIndex == 2 ? Color(0xFF5572B5) : Colors.transparent),
                                                            borderRadius: BorderRadius.circular(3),
                                                          ),
                                                          padding: EdgeInsets.all(3),
                                                          child: Text(dataArr[rowIndex], style: TextStyle(fontSize: rowIndex == 0 ? 10 : 13, color: rowIndex == 0 ? (isDarkMode ? Colors.grey : Colors.black) : Colors.white),),
                                                        ),
                                                        alignment: Alignment.center,
                                                      );
                                                    }),
                                                  ),
                                                );
                                              },
                                              childCount: _xList.length + 1,
                                            ),

                                          ),
                                        ],

                                      ),
                                    ),
                                  ),

                                  InkWell(
                                    onTap: () {
                                      isExpand = !isExpand;
                                      setState(() {});
                                    },
                                    child: Container(
                                      // height: 70,
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: [
                                          Text(LocaleKeys.device_info_check_list.trc(), style: TextStyle(color: Color(0xFFAAAAAA)),),
                                          Image.asset(isExpand ? IconNames.tep_zhankai2 : IconNames.tep_zhankai, width: 25,),
                                        ],
                                      ),
                                      alignment: Alignment.center,
                                      margin: EdgeInsets.fromLTRB(0, 10, 0, 20),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),

                  ],
                ),
              ),
            ),

            Container(
              height: 60,
              width: MainCommon.screenWidth,
              color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: _itemList.map((e) {
                  final index = _itemList.indexOf(e);
                  bool isChushi = LocalStorage.getRole() == "1" && index == 1;
                  bool isDark = isDarkMode && isChushi;

                  return InkWell(
                    onTap: () {
                      if(index == 0) {
                        Get.toNamed(e["route"], arguments: _productId)?.then((value) {
                          _getDeviceInfo();
                        });
                      }else if(index == 1){  //设置参数
                        if(isChushi) return;  // 厨师不可设置参数

                        Get.toNamed(e["route"], arguments: [_productId])?.then((value) {
                          _getDeviceInfo();
                        });
                      } else{
                        Get.toNamed(e["route"], arguments: _productId)?.then((value) {
                          _getDeviceInfo();
                        });
                      }
                      _stopRefreshTimer();
                    },
                    child: Container(
                      width: MainCommon.screenWidth / 3.0,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.asset(e["icon"], height: 30, color: isDark ? Colors.black.withOpacity(0.5) : (isChushi ? Colors.grey.shade200 : null),),
                          Text(e["title"], style: TextStyle(color: isDark ? Colors.black.withOpacity(0.5) : (isChushi ? Colors.grey.shade300 : Colors.grey), fontSize: 13),),
                        ],
                      ),
                    ),
                  );
                }).toList(),
              ),
            ),

          ],
        ),
      ),
    );
  }

  // 获取设备数据
  _getDeviceInfo() async {
    final params = {"productId": "${_productId}"};
    ResultData data = await AppApi.getInstance().getProductInfo(params);
    if(data.code == 0){
      _productModel = ProductModel.fromJson(data.data);
      setState(() {});

      // SmartDialog.showToast("success");
    }else {
      SmartDialog.showToast(data.msg);
    }
  }

  // 获取温度数据
  _getTempList() async {
    List typeList = [
      8, 1, 2, 3, 4, 5, 6,
      // LocaleKeys.device_info_one_day.trc(),
      // LocaleKeys.device_info_one_week.trc(),
      // LocaleKeys.device_info_one_month.trc(),
      // LocaleKeys.device_info_three_month.trc(),
      // LocaleKeys.device_info_half_year.trc(),
      // LocaleKeys.device_info_one_year.trc(),
      // LocaleKeys.device_info_one_hour.trc(),
    ];

    int currentValue = tabSelectIndex == 0 ? 8 : tabSelectIndex;

    final params = {"productId": "${_productId}", "type": "${currentValue}"};
    ResultData data = await AppApi.getInstance().getTempList(params);
    if(data.code == 0){
      final xList = data.data["xAxis"] as List;
      final yList = data.data["yAxis"] as List;

      final weekList = [
        LocaleKeys.other_w_1.trc(), LocaleKeys.other_w_2.trc(),
        LocaleKeys.other_w_3.trc(),LocaleKeys.other_w_4.trc(),
        LocaleKeys.other_w_5.trc(),LocaleKeys.other_w_6.trc(),
        LocaleKeys.other_w_7.trc(),
      ];
      _xList = xList.map((e){
        final index = xList.indexOf(e);
        if(currentValue == 2){
          return weekList[index];
        }
        return e.toString();
      }).toList();
      _x2List = _xList;

      yList.forEach((element) {
        final name = element["name"];
        final data = element["data"] as List;
        final dataList = data.map((e) => double.parse(e.toString())).toList();
        if(name == "T1") {
          _yList = dataList;
        }else if(name == "T2") {
          _y2List = dataList;
        }
      });
      if(yList.isEmpty) {
        _yList = xList.map((e) => 0.0).toList();
        _y2List = _yList;
      }

      setState(() {});
    }else {
      // SmartDialog.showToast(data.msg);
    }
  }

  _startTimer() {

    _refreshTimer ??= Timer.periodic(Duration(seconds: 60), (timer) {
      _getDeviceInfo();
      _getTempList();
    });
  }
  _stopRefreshTimer(){
    if(_refreshTimer != null){
      _refreshTimer?.cancel();
    }
  }

  // 显示 Dialog
  _showExportFileDialog() {
    showDialog(context: context, builder: (ctx) {
      return AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        contentPadding: EdgeInsets.fromLTRB(0, 0, 0, 0),
        titlePadding: EdgeInsets.fromLTRB(0, 10, 0, 10),
        title: Text(LocaleKeys.other_export_file.trc(), textAlign: TextAlign.center, style: TextStyle(color: Colors.grey, fontSize: 15),),
        content: ItemSelectWidget(
          titleArr: ["Excel", "PDF"],
          selectIndex: -1,
          selectActionValue: (value) {
            if(value == 0){
              _exportExcel();
            }else if(value == 1){
              _exportPDF();
            }
            Get.back();
          },
        ),
      );
    });

  }

  _exportExcel() async {
    // 创建一个Excel文件
    final Flutter_Xlsio.Workbook workbook = Flutter_Xlsio.Workbook();
    // 选择一个工作表
    final Flutter_Xlsio.Worksheet sheet = workbook.worksheets[0];

    // 设置标题
    sheet.getRangeByName('A1').setText(_typeList[tabSelectIndex]);
    sheet.getRangeByName('B1').setText("T1");
    sheet.getRangeByName('C1').setText("T2");
    // 垂直方向文字
    sheet.getRangeByName('A1').cellStyle.hAlign = Flutter_Xlsio.HAlignType.center;
    sheet.getRangeByName('B1').cellStyle.hAlign = Flutter_Xlsio.HAlignType.center;
    sheet.getRangeByName('C1').cellStyle.hAlign = Flutter_Xlsio.HAlignType.center;
    sheet.getRangeByName('A1').cellStyle.backColorRgb = Colors.blue;
    sheet.getRangeByName('B1').cellStyle.backColorRgb = Colors.blue;
    sheet.getRangeByName('C1').cellStyle.backColorRgb = Colors.blue;
    sheet.getRangeByName('A1').cellStyle.fontColorRgb = Colors.white;
    sheet.getRangeByName('B1').cellStyle.fontColorRgb = Colors.white;
    sheet.getRangeByName('C1').cellStyle.fontColorRgb = Colors.white;
    // 设置内容
    for(int i = 0; i < _xList.length; i++){
      // 第一列
      sheet.getRangeByIndex(i + 2, 1).setText(_xList[i].toString());
      sheet.getRangeByIndex(i + 2, 1).cellStyle.hAlign = Flutter_Xlsio.HAlignType.center;
      // 第二列
      sheet.getRangeByIndex(i + 2, 2).setText(_yList[i].toString());
      sheet.getRangeByIndex(i + 2, 2).cellStyle.hAlign = Flutter_Xlsio.HAlignType.center;
      // 第三列
      sheet.getRangeByIndex(i + 2, 3).setText(_y2List[i].toString());
      sheet.getRangeByIndex(i + 2, 3).cellStyle.hAlign = Flutter_Xlsio.HAlignType.center;
    }

    // save and dispose the workbook.
    final List<int> bytes = workbook.saveAsStream();
    workbook.dispose();
    // File('Chart.xlsx').writeAsBytes(bytes);
    
    final Directory directory = await getApplicationDocumentsDirectory();
    // Directory directory = Platform.isAndroid ? await getExternalStorageDirectory() : await getApplicationDocumentsDirectory();

    //
    var fileName = "${_productModel.code}_${_productModel.modelName}";
    if(_productModel.name.isNotEmpty){
      fileName += _productModel.name;
    }

    fileName += "_" + formatDate(DateTime.now(), [yyyy, mm, dd, HH]) + "_" + _getTimeType();

    final String path = directory.path;
    final File file = File('$path/${fileName}.xlsx');
    file.writeAsBytes(bytes);

    ShareExtend.share(file.path, "file");
  }

  _exportPDF() async {
    final pdfData = await buildPdf(
      PdfPageFormat(
          210 * PdfPageFormat.mm, 297 * PdfPageFormat.mm,
          marginAll: 3 * PdfPageFormat.mm),
      _getTimeType(),
      _xList,
      _yList,
      _y2List,
    );

    var fileName = "${_productModel.code}_${_productModel.modelName}";
    if(_productModel.name.isNotEmpty){
      fileName += "_" + _productModel.name;
    }
    fileName += "_" + formatDate(DateTime.now(), [yyyy, mm, dd, HH]) + "_" + _getTimeType();

    // 直接分享
    Printing.sharePdf(bytes: pdfData, filename: "$fileName.pdf");

    return;
    Printing.layoutPdf(
      onLayout: (PdfPageFormat format) {
        return pdfData;
      },
    );

  }

  String _getTimeType() {
    List typeList = [
      "1 hr",
      "1 D",
      "1 Wk",
      "1 mth",
      "3 mths",
      "6 mths",
      "12 mths",
    ];
    return typeList[tabSelectIndex];
  }

  // 设置冷凝器报警清零
  _lengningqiClear() {
    showOkCancelAlertDialog(
      context: context,
      message: LocaleKeys.other_clear_warn.trc(),
      builder: (context, child) => Theme(
        data: ThemeData(
            primarySwatch: createMaterialColor(isDarkMode ? Colors.white : Colors.black),
            dialogBackgroundColor: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
            colorScheme: ColorScheme(
              primary: isDarkMode ? Colors.white : Colors.black, // 文字颜色
              primaryVariant: Colors.white,
              secondary: Colors.green,
              background: Colors.white,
              error: Colors.red,
              brightness: isDarkMode ? Brightness.dark : Brightness.light,    /// 最最关键
              onBackground: Colors.pink,
              secondaryVariant: Colors.white,
              onError: Colors.yellow,
              onPrimary: Colors.red, //顶部栏字体颜色
              onSecondary: Colors.black,
              onSurface: Colors.white,   // 导航栏字体颜色, 返回按钮颜色
              surface: MainCommon.darkBlueMaterialColor,  // 导航栏背景颜色
            )),
        child: child,
      ),

    ).then((value) {
      if(value == OkCancelResult.ok){
        _configDeviceParams();
      }
    });
  }

  _configDeviceParams() async {
    // 获取服务端设置的 custom code
    final params = {"productId": "${_productId}"};
    ResultData data = await AppApi.getInstance().getSettingInfo(params);
    if(data.code == 0){
      final paramsList = data.data["productSettingValue"] as List;
      paramsList.forEach((element) {
        final code = element["code"];
        final customCode = element["customCode"];

        bool isACClear = code.toLowerCase() == "ac" && _productModel.condenserClean.isNotEmpty;
        bool isADClear = code.toLowerCase() == "ad" && (_productModel.highTemperature.isNotEmpty || _productModel.lowerTemperature.isNotEmpty);
        if(isACClear) {  // isADClear, 只清除AC
          SmartDialog.showLoading();  // 正在配置中
          TySmartHome.updateDeviceDPS(_productModel.devId, customCode.toLowerCase(), 0).then((value) {
            if(value == true) {   // 更改成功
              SmartDialog.dismiss();
              SmartDialog.showToast("Success");
            }else{
              SmartDialog.showToast(LocaleKeys.add_device_config_fail.trc());
            }
          });
        }
      });
    }
  }


}
